package user

import (
	"context"
	protos "goim-pro/api/protos/salty"
	"goim-pro/internal/app/services/converters"
	usersrv "goim-pro/internal/app/services/user"
	errmsg "goim-pro/pkg/errors"
	"goim-pro/pkg/logs"
	"goim-pro/pkg/utils"
)

var (
	logger      = logs.GetLogger("INFO")
	userService *usersrv.UserService
)

type userServer struct {
}

func New() protos.UserServiceServer {
	userService = usersrv.New()
	return &userServer{}
}

func (u *userServer) UpdateUserProfile(ctx context.Context, req *protos.GrpcReq) (resp *protos.GrpcResp, grpcErr error) {
	resp, _ = utils.NewGRPCResp(protos.StatusCode_STATUS_OK, nil, "")

	var err error
	var updateUserProfileReq protos.UpdateUserProfileReq
	if err = utils.UnmarshalGRPCReq(req, &updateUserProfileReq); err != nil {
		resp.Code = protos.StatusCode_STATUS_BAD_REQUEST
		resp.Message = err.Error()
		logger.Errorf(`unmarshal error: %v`, err)
		return
	}

	// will over write the token value at rpc interceptor
	userId := req.GetUserId()
	pbProfile := updateUserProfileReq.GetUser()
	if pbProfile == nil {
		resp.Code = protos.StatusCode_STATUS_BAD_REQUEST
		resp.Message = errmsg.ErrInvalidParameters.Error()
		return
	}
	userProfile := converters.ConvertProto2EntityForUserProfile(pbProfile)
	userProfile.UserId = userId

	if tErr := userService.UpdateUserInfo(userId, &userProfile); tErr != nil {
		resp.Code = tErr.Code
		resp.Message = tErr.Detail
		return
	}
	return
}

func (u *userServer) QueryUserProfile(ctx context.Context, req *protos.GrpcReq) (resp *protos.GrpcResp, gRPCErr error) {
	resp, _ = utils.NewGRPCResp(protos.StatusCode_STATUS_OK, nil, "")

	var err error
	var queryUserProfileReq protos.QueryUserProfileReq
	if err = utils.UnmarshalGRPCReq(req, &queryUserProfileReq); err != nil {
		resp.Code = protos.StatusCode_STATUS_BAD_REQUEST
		resp.Message = err.Error()
		logger.Errorf(`unmarshal error: %v`, err)
		return
	}

	telephone := queryUserProfileReq.GetTelephone()
	email := queryUserProfileReq.GetEmail()
	if utils.IsEmptyStrings(telephone, email) {
		resp.Code = protos.StatusCode_STATUS_BAD_REQUEST
		resp.Message = errmsg.ErrInvalidParameters.Error()
		return
	}

	userInfo, tErr := userService.QueryUserProfile(telephone, email)
	if tErr != nil {
		resp.Code = tErr.Code
		resp.Message = tErr.Detail
		return
	}

	userInfoResp := &protos.QueryUserProfileResp{
		User: converters.ConvertEntity2ProtoForUserProfile(*userInfo),
	}
	resp.Data, err = utils.MarshalMessageToAny(userInfoResp)
	if err != nil {
		logger.Errorf("[queryUserInfo] response marshal message error: %s", err.Error())
	}
	return
}
